﻿using AuthenticationAPI.Models;
using AuthenticationAPI.Models.DbContext;
using AuthenticationAPI.Models.Utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AuthenticationAPI.Controllers
{
    public class UserController : ApiController
    {

        /// <summary>
        /// 获取申请者的信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        [Route("api/user/{userName}/applier")]
        [HttpGet]
        public HttpResponseMessage GetAppliers(string userName)
        {
            using (var db = new AuthenticationEntities())
            {
                var reviewer = db.User.Single(p => p.UserName == userName);
                var appliers = db.Candidate.Where(p => p.Reviewer == userName).ToList();
                return Request.CreateResponse(HttpStatusCode.OK, appliers.ToList());

            }
        }

        /// <summary>
        /// 管理员批准一个账号
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        [Route("api/user/{userName}/approveaccount")]
        [HttpPost]
        public HttpResponseMessage ApproveAccount(string userName, [FromBody]string jsonStr)
        {
            var applier = JsonConvert.DeserializeObject<Applier>(jsonStr);
            using (var db = new AuthenticationEntities())
            {
                var rewiewerFull = db.User.SingleOrDefault(p => p.UserName == userName);
                var candidate = db.Candidate.FirstOrDefault(p => p.UserName == applier.ApplierUserName && p.Reviewer == rewiewerFull.UserName);
                if (rewiewerFull != null && candidate != null)
                {
                    if (applier.Accept == true)
                    {
                        //被批准
                        var user = new User()
                        {
                            UserName = candidate.UserName,
                            Password = candidate.Password,
                            Phone = candidate.Phone,
                            RealName = candidate.RealName,
                            Corporation = rewiewerFull.Corporation,
                            Department = applier.Department,
                            Mail = candidate.Mail,
                            Authentication = applier.Authentication,
                            Avatar = UserHelper.avatarGenerator()
                        };
                        db.User.Add(user);
                        db.Candidate.Remove(candidate);
                        //添加权限项目
                        if (applier.AuthorizedProjectList.Count > 0)
                        {
                            var list = from p in applier.AuthorizedProjectList
                                       select new AuthorizedProject()
                                       {
                                           Operation = "",
                                           PrjId = p,
                                           UserName = applier.ApplierUserName
                                       };
                            db.AuthorizedProject.AddRange(list);
                        }
                    }
                    //被拒绝
                    else
                    {
                        db.Candidate.Remove(candidate);
                    }

                    db.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Done");
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.InternalServerError, "不存在的人员!");
                }

            }
        }

        [Route("api/user/{userName}/changepassword")]
        [HttpPost]
        public HttpResponseMessage ChangePassword(string userName, [FromBody]string jsonStr)
        {
            var jsonData = JObject.Parse(jsonStr);
            var logInfo = JsonConvert.DeserializeObject<loginUser>(jsonStr);
            using (var db = new AuthenticationEntities())
            {
                var tempUser = db.User.SingleOrDefault(p => p.UserName.ToLower() == userName
                    .ToLower() && p.Password == logInfo.password);
                if (tempUser == null)
                {
                    return Request.CreateResponse(HttpStatusCode.Forbidden, "Access Denied!");
                }
                else
                {
                    tempUser.Password = jsonData["newPassword"].ToString();
                    db.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, true);
                }
            }
        }

        [Route("api/user/{userName}/updateInfo")]
        [HttpPost]
        public HttpResponseMessage UpdateInfo(string userName, [FromBody]string jsonStr)
        {

            var userInfo = JsonConvert.DeserializeObject<User>(jsonStr);
            using (var db = new AuthenticationEntities())
            {
                var user = db.User.SingleOrDefault(p => p.UserName == userName);
                user.Phone = userInfo.Phone;
                user.Mail = userInfo.Mail;
                if (userInfo.Avatar != null && userInfo.Avatar != "")
                {
                    user.Avatar = userInfo.Avatar;
                }
                db.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK, true);
            }
        }


        [Route("api/user/{userName}/authorizedUsers")]
        [HttpGet]
        public HttpResponseMessage GetAuthorizedUsers(string userName)
        {
            var list = UserHelper.GetAuthorizedUsers(userName);
            return Request.CreateResponse(HttpStatusCode.OK, list);

        }


        [Route("api/user/{userName}/freezeUser")]
        [HttpPost]
        public HttpResponseMessage FreezeUser(string userName, [FromBody] string jsonStr)
        {
            using (var db = new AuthenticationEntities())
            {
                //序列化得来的user
                var user = JsonConvert.DeserializeObject<User>(jsonStr);
                //数据库中存在的user
                var exsited = db.User.SingleOrDefault(t => t.UserName == user.UserName);
                if (user == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, false);
                }
                exsited.Freeze = user.Freeze;
                db.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK, true);

            }
        }


        [Route("api/user/{userName}/updateUserAuthorizedProjectList")]
        [HttpPost]
        public HttpResponseMessage UpdateUserAuthorizedProjectList(string userName, [FromBody] string jsonStr)
        {
            using (var db = new AuthenticationEntities())
            {
                //数据库中存在的user
                var user = db.User.SingleOrDefault(t => t.UserName == userName);
                if (user == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, false);
                }


                //序列化得来的authorizedPrjList
                var authorizedPrjList = JsonConvert.DeserializeObject<List<AuthorizedProject>>(jsonStr);
                var shouldAddList = (from p in authorizedPrjList
                                     where p.Remark == "true"
                                     select new AuthorizedProject()
                                     {
                                         UserName = p.UserName,
                                         PrjId = p.PrjId,
                                         Operation = ""
                                     }).ToList();

                var shouldDeleteList = (from p in authorizedPrjList
                                        from q in db.AuthorizedProject
                                        where p.Remark == "false" && p.UserName == q.UserName && p.PrjId == q.PrjId
                                        select q).ToList();

                db.AuthorizedProject.RemoveRange(shouldDeleteList);
                db.AuthorizedProject.AddRange(shouldAddList);
                db.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK, true);

            }
        }

        [Route("api/user/{userName}/changeUserAuthentication")]
        [HttpPost]
        public HttpResponseMessage ChangeUserAuthentication(string userName, [FromBody] string jsonStr)
        {
            var user = JsonConvert.DeserializeObject<userInfo>(jsonStr);
            using (var db = new AuthenticationEntities())
            {
                var operater = db.User.SingleOrDefault(t => t.UserName == userName);

                var target = db.User.SingleOrDefault(t => t.UserName == user.userName);

                if (operater == null || target == null)
                {
                    return Request.CreateResponse(HttpStatusCode.Forbidden, false);

                }
                else
                {
                    target.Authentication = user.authentication;
                    db.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, true);
                }

            }

        }

        /// <summary>
        /// 获取用户要审核的项目
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        [Route("api/user/{userName}/needReviewProjects")]
        [HttpGet]
        public HttpResponseMessage GetReviewProjects(string userName)
        {
            using (var db = new AuthenticationEntities())
            {

                var prjList = UserHelper.GetAuthorizedProjects(userName);

                using (var prjDb = new MetroProjectsEntities())
                {
                    var list = (from p in prjDb.PointsSummaryNeedToBeRevieweds
                                where prjList.Contains(p.PrjId)
                                group p by new { p.PrjId, p.DateTime } into g
                                select g
                                ).ToList().Select(g => new
                                {
                                    prjName = prjDb.Projects.FirstOrDefault(p => p.PrjId == g.Key.PrjId).Name,
                                    prjId = g.Key.PrjId,
                                    prjType = prjDb.Projects.FirstOrDefault(p => p.PrjId == g.Key.PrjId).ProjectType,
                                    date = g.Key.DateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                    monitorTypes = (from t in g group t by t.MonitorType into a select a.Key).ToList(),
                                    items = from t in g
                                            select new
                                            {
                                                monitorType = t.MonitorType,
                                                location = t.Location
                                            }

                                }).ToList();
                    return Request.CreateResponse(HttpStatusCode.OK, list);
                }
            }
        }

        /// <summary>
        /// 用户审核一个项目
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="prjId"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [Route("api/user/{userName}/ReviewProject")]
        [HttpPost]
        public HttpResponseMessage ReviewProject(string userName, [FromBody]string jsonStr)
        {
            var Jobject = JObject.Parse(jsonStr);

            var date = Jobject["date"].ToObject<DateTime>();
            var prjId = Jobject["prjId"].ToObject<int>();
            var action = Jobject["action"].ToObject<int>();
            ReviewProjectHelper.ReviewProject(prjId, date, action);
            return Request.CreateResponse(HttpStatusCode.OK, "Done!");
        }

        /// <summary>
        /// 用户审核一个项目
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="prjId"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [Route("api/user/{userName}/ReviewProject/{prjId}/date/{dateStr}/action/{pass}")]
        [HttpGet]
        public HttpResponseMessage ReviewProjectGet(string userName, int prjId, string dateStr, int pass)
        {
            var date = DateTime.Parse(dateStr);
            ReviewProjectHelper.ReviewProject(prjId, date, pass);
            return Request.CreateResponse(HttpStatusCode.OK, "Done!");
        }
    }
}
